package com.tian.arch.function.permission

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

/**
 * 在activity中进行权限申请，实现的逻辑是在activity添加一个没有界面的Fragment来做到
 */
class ActivityPermissionRequest(private val activity: AppCompatActivity) : PermissionRequest() {

    private var reqFragment: IRequestPermission? = null

    override fun provideContext(): Context {
        return activity
    }

    override fun shouldShowRequestPermissionRationale(vararg permission: String): Boolean {
        permissions?.forEach {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, it)) {
                return false
            }
        }
        return true
    }

    override fun requestPermissions() {
        if (reqFragment == null) {
            activity.supportFragmentManager.run {
                reqFragment = RealReqPermissionFragment()
                beginTransaction().add(reqFragment!! as RealReqPermissionFragment, "RealReqPermissionFragment").commitNowAllowingStateLoss()
            }
        }
        permissions?.let { reqFragment?.reqPermissions(*it) }
    }

    override fun openAppSetting() {
        reqFragment?.openAppSetting()
    }
}